<template>
  <div class="update-name">
    <!-- 导航栏 -->
    <van-nav-bar
      title="修改昵称"
      left-text="取消"
      right-text="完成"
      @click-left="$emit('close')"
      @click-right="onUpdate"
    />

    <!-- 输入框 -->
    <div class="field-warp">
      <van-field
        v-model.trim="localName"
        rows="2"
        autosize
        type="textarea"
        maxlength="15"
        placeholder="请输入昵称"
        show-word-limit
      />
    </div>

    <!-- 输入框 -->
  </div>
</template>

<script>
// 关闭弹层 通知父组件$emit('名字close')
import { updateUserName } from "@/api/user.js";
export default {
  name: "UpdateName",
  data() {
    return {
      // 双向绑定让value作为初始值   将message改为localname
      localName: this.value, //让他作为初始值
    };
  },
  props: {
    //   父组件v-model 绑定  子组件props接收value属性内容
    value: {
      type: String,
      required: true,
    },
  },
  methods: {
    //   点击完成事件
    async onUpdate() {
      this.$toast.loading({
        message: "保存中",
        forbidClick: true, //禁止背景点击
        duration: 0, //持续展示
      });
      try {
        const localName = this.localName;
        if (!localName.length) {
          alert("昵称不能为空");
          return;
        }
        const { data } = await updateUserName({
          name: this.localName,
          // 修改谁就写谁
        });
        console.log(data);
        // v-modle触发input事件
        // 视图更新

        this.$emit("input", this.localName);

        // 关闭弹层
        this.$emit("close");
        // 提示成功;
        this.$toast.success("更新成功");
      } catch (err) {
        this.$toast.fail("昵称更新失败");
      }
    },
  },
  created() {
    this.localName = this.value;
  },
};
</script>

<style scoped lang="less">
.field-warp {
  padding: 20px;
}
</style>